/**
 *  @author Morozan Ion
 *  
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.dddforandroid.c2dm;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.dddforandroid.util.Util;
import com.google.appengine.api.NamespaceManager;

/**
 * Authenticate on the server side to c2dm protocol. After this, the current
 * server will be an proxy to real c2dm servers.
 * 
 * 
 */
public class AuthenticationUtil {

	public static final String AUTHENTICATION_ENDPOINT = "https://www.google.com/accounts/ClientLogin";

	public static String getTokenFromServer(String email, String password)
			throws IOException {

		/** Create a namespace for Admin user. */
		NamespaceManager.set(Util.ADMIN_NAMESPACE);

		/**
		 * Create the post data Requires a field with the email and the password
		 */
		StringBuilder builder = new StringBuilder();
		builder.append("Email=").append(email);
		builder.append("&Passwd=").append(password);
		builder.append("&accountType=GOOGLE");
		builder.append("&source=DDDForAndroid");
		builder.append("&service=ac2dm");

		/** Setup the Http Post */
		byte[] data = builder.toString().getBytes();
		URL url = new URL(AUTHENTICATION_ENDPOINT);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setUseCaches(false);
		con.setDoOutput(true);
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		con.setRequestProperty("Content-Length", Integer.toString(data.length));

		/** Issue the HTTP POST request */
		OutputStream output = con.getOutputStream();
		output.write(data);
		output.close();

		/** Read the response */
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		String line = null;
		String auth_key = null;
		while ((line = reader.readLine()) != null) {
			if (line.startsWith("Auth=")) {
				auth_key = line.substring(5);
			}
		}

		/**
		 * Finally get the authentication token and add it to database in admin
		 * namespace
		 * */
		Util.updateToken(auth_key);

		return auth_key;
	}
}